package im.ok.back.service.impl;

import cn.hutool.core.lang.UUID;
import com.alibaba.excel.EasyExcelFactory;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import im.ok.back.common.ServerResponse;
import im.ok.back.dao.FeedBackMapper;
import im.ok.back.pojo.FeedBack;
import im.ok.back.service.IFeedBackService;
import im.ok.back.util.excel.FeedbackDTO;
import im.ok.back.util.excel.FeedbackExcelListener;
import im.ok.back.vo.FeedBackQuery;
import im.ok.back.vo.ListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class FeedBackServiceImpl implements IFeedBackService {

    @Autowired
    private FeedBackMapper feedBackMapper;

    @Override
    public ServerResponse add(FeedBack feedBack) {
        feedBack.setId(UUID.randomUUID().toString(true));
        int resultCount = feedBackMapper.insertSelective(feedBack);
        if (resultCount != 0) {
            return ServerResponse.createSuccess();
        }
        return ServerResponse.createSuccessMessage("添加失败");
    }

    @Override
    public ServerResponse delete(String id) {
        int resultCount = feedBackMapper.deleteById(0, id);
        if (resultCount == 0) {
            return ServerResponse.createSuccessMessage("删除失败");
        }
        return ServerResponse.createSuccess();
    }

    @Override
    public ServerResponse getList(FeedBackQuery feedBackQuery) {
        List<FeedBack> list = PageHelper.startPage(feedBackQuery.getPage(), feedBackQuery.getLimit()).doSelectPage(()-> feedBackMapper.selectSelective(feedBackQuery));
        if (list != null) {
            ListVo listVo = new ListVo();
            listVo.setItems(list);
            listVo.setTotal(PageHelper.count(()->feedBackMapper.selectSelective(feedBackQuery)));
            return ServerResponse.createSuccessData(listVo);
        }
        return ServerResponse.createError("获取反馈列表失败");
    }

    @Override
    public ServerResponse importData(MultipartFile file) {
        try {
            EasyExcelFactory.read(file.getInputStream(), FeedbackDTO.class, new FeedbackExcelListener(feedBackMapper)).headRowNumber(1).build().readAll();
            return ServerResponse.createSuccessMessage("导入成功！");
        } catch (IOException e) {
            log.error("import error:", e);
        }
        return ServerResponse.createError("导入失败！");
    }
}
